package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper,Serve> implements IServeService {
    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private ServeMapper serveMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }
    /**
     * 服务搜索
     * @param cityCode
     * @param keyword
     * @param serveTypeId
     * @return
     */
    @Override
    public List<ServeSimpleResDTO> search(String cityCode, String keyword, Long serveTypeId) {
        //1.构建请求对象
        SearchRequest request = new SearchRequest("serve_aggregation");

        //2.封装请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //城市编码
        boolQuery.must(QueryBuilders.termQuery("city_code", cityCode));
        //服务类型id
        if (serveTypeId != null) {
            boolQuery.must(QueryBuilders.termQuery("serve_type_id", serveTypeId));
        }
        //关键词
        if (StrUtil.isNotEmpty(keyword)){
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword,"serve_item_name", "serve_type_name"));
        }

        request.source().query(boolQuery);//查询
        request.source().sort("serve_item_sort_num", SortOrder.ASC);//排序

        //3.执行查询
        try {
            //4.处理返回结果
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            if (response.getHits().getTotalHits().value == 0){
                return List.of();
            }

            return Arrays.stream(response.getHits().getHits()).map(e ->
                    JSONUtil.toBean(e.getSourceAsString(), ServeSimpleResDTO.class)
            ).collect(Collectors.toList());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 区域服务分类
     * @param regionId
     * @return
     */
    @Override
    public List<ServeAggregationTypeSimpleResDTO> serveTypeList(Long regionId) {
        // 1.对区域进行校验
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus()!=2){
            return List.of();
        }

        // 2.查询当前区域下上架服务对应的分类
        return serveMapper.findServeTypeList(regionId);
    }

    @Override
    public ServeAggregationSimpleResDTO findById(Long id) {
        //1. 根据服务id去serve表中查询服务信息(内含服务项目id)
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus()!=2){
            throw new ForbiddenOperationException("服务不存在");
        }

        //2. 根据服务项目id去serve_item表中查询服务项目信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus()!=2){
            throw new ForbiddenOperationException("服务项目不存在");
        }

        //3. 将两部分内容组装成返回结果
        ServeAggregationSimpleResDTO dto = BeanUtil.toBean(serve, ServeAggregationSimpleResDTO.class);
        dto.setServeItemName(serveItem.getName());
        dto.setServeItemImg(serveItem.getImg());
        dto.setDetailImg(serveItem.getDetailImg());
        dto.setUnit(serveItem.getUnit());

        return dto;
    }

    /**
     * 精选推荐
     * @param regionId
     * @return
     */
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key ="#regionId" ,
                            unless ="#result.size() > 0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key ="#regionId" ,
                            unless ="#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
//    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,key = "#regionId")
    @Override
    public List<ServeCategoryResDTO> hotServeList(Long regionId) {
        // 1.查询区域的信息
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus()!=2){
            throw new ForbiddenOperationException("区域不存在或状态不正确");
        }

        // 2.调用mapper根据区域id查询服务列表
        List<ServeCategoryResDTO> serveList = baseMapper.findServeListByRegionId(regionId);
        return serveList;
    }

    /**
     * 首页区域服务列表
     * @param regionId
     * @return
     */
    /*
    在Cacheable注解中有两个属性可以指定条件进行缓存
    condition：对方法参数进行判断，只缓存符合条件的
    unless：对方法返回结果进行判断，只缓存不符合条件的
     */
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() > 0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
//    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId")
    @Override
    public List<ServeCategoryResDTO> firstPageServeList(Long regionId) {
        // 1.查询区域的信息
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus()!=2){
            throw new ForbiddenOperationException("区域不存在或状态不正确");
        }
        // 2.调用mapper根据区域id查询首页服务列表
        List<ServeCategoryResDTO> list= baseMapper.findListByRegionId(regionId);
        if (CollectionUtil.isEmpty(list)){
            return List.of();
        }
        // 3.截取
        //服务类型
//        list=list.subList(0,Math.min(list.size(),2));
//        list.forEach(e -> {
//            List<ServeSimpleResDTO> serveResDTOList = e.getServeResDTOList();
//            serveResDTOList=serveResDTOList.subList(0,Math.min(serveResDTOList.size(),4)); //服务类型
//            e.setServeResDTOList(serveResDTOList);
//        });

        list = CollUtil.sub(list, 0, Math.min(list.size(), 2));//服务类型截取
        list.forEach(e ->
                //服务项目截取
                e.setServeResDTOList(CollUtil.sub(e.getServeResDTOList(), 0, Math.min(e.getServeResDTOList().size(), 4)))
        );

        return list;
    }

    /**
     * 区域服务分页查询
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> findByPage(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryList(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 批量新增区域服务
     * for循环多次操作表，因尽量放在一个集合一次操作表
     * @param dtoList
     */
    @Override
    public void add(List<ServeUpsertReqDTO> dtoList) {
        for (ServeUpsertReqDTO serveUpsertReqDTO : dtoList) {
            //1．服务项目必须是启用状态的才能添加到区域（根据服务项目id查询serve_item表)
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if (serveItem==null || serveItem.getActiveStatus()!=2){
                throw new ForbiddenOperationException("服务项不存在或状态不正确");
            }

            //2.一个服务项目对于一个区域，只能添加一次
            LambdaQueryWrapper<Serve> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Serve::getRegionId,serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId,serveUpsertReqDTO.getServeItemId());
            Integer i = baseMapper.selectCount(wrapper);
            if (i>0){
                throw new ForbiddenOperationException("服务项已经添加过了");
            }
            //保存
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serve.getRegionId());
            if (region !=null){
                serve.setCityCode(region.getCityCode());
            }
            baseMapper.insert(serve);
        }
    }

    /**
     * 删除区域服务
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //1.根据id查询服务的状态如果状态不是草稿，则删除失败
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus()!=0){
            throw new ForbiddenOperationException("服务项不存在或状态不正确");
        }
        // 2.执行删除
        baseMapper.deleteById(id);
    }

    /**
     * 上架
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onSale(Long id) {
        // 1.区域服务当前非上架状态
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus()==2){
            throw new ForbiddenOperationException("当前服务已经是上架状态了");
        }
        // 2.服务项目是启用状态
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus()!=2){
            throw new ForbiddenOperationException("当前项目未启用");
        }

        // 3.执行上架
        serve.setSaleStatus(2);
        baseMapper.updateById(serve);

        //4）添加同步表数据
        addServeSync(id);
    }

    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;


    /**
     * 新增服务同步数据
     *
     * @param serveId 服务id
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }

    /**
     * 区域服务下架
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void offSale(Long id) {
        //区域服务当前为上架状态才可下架
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus()!=2){
            throw new ForbiddenOperationException("当前服务项不是上架状态");
        }
//        serve.setSaleStatus(0);
        serve.setSaleStatus(1);
        baseMapper.updateById(serve);

        //从服务同步表删除服务数据
        serveSyncMapper.deleteById(id);
    }

    /**
     * 区域服务设置热点
     * @param id
     */
    @Override
    public void updateOnHot(Long id) {
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("服务项不存在");
        }
        if (serve.getIsHot()==1){
            throw new ForbiddenOperationException("当前服务项已经是热门");
        }
        if (serve.getSaleStatus()!=2){
            throw new ForbiddenOperationException("当前服务项未上架");
        }
        serve.setIsHot(1);
        serve.setHotTimeStamp(System.currentTimeMillis());
        baseMapper.updateById(serve);
    }

    /**
     * 取消热门
     * @param id
     */
    @Override
    public void updateOffHot(Long id) {
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("服务项不存在");
        }
        serve.setIsHot(0);
        //清空时间戳
        serve.setHotTimeStamp(null);
        serveMapper.updateOffHot(serve);
    }

}
